package cn.jiyun.security;

import cn.jiyun.entity.UserInfo;
import cn.jiyun.pojo.Role;
import cn.jiyun.service.TeacherService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SpringSecurityUserService2 implements UserDetailsService {

/*    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;*/

    @Reference
    private TeacherService teacherService;


    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      cn.jiyun.pojo.User user = teacherService.findByUserName(username);
        if(user==null){
            return null;
        }

        //模拟查询数据库中用户的密码
        String password = "{noop}"+user.getPwd();
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
        //授权，后期需要改为查询数据库动态获得用户拥有的权限和角色
       List<Role> roleList =  teacherService.findByUid(user.getId());
        for (Role role : roleList) {
            list.add(new SimpleGrantedAuthority(role.getName()));
        }
        return new User(username, password, list);
    }
}
